package com.wangshaoyu.music_player.controller;

import com.wangshaoyu.music_player.data_object.UserDo;
import com.wangshaoyu.music_player.repository.UserRepo;
import com.wangshaoyu.music_player.session_object.UserSO;
import com.wangshaoyu.org.mindrot.jbcrypt.BCrypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/studio/user")
public class StudioUserDoController {
    private final UserRepo userRepo;

    @Autowired
    public StudioUserDoController(UserRepo userRepo) {
        this.userRepo = userRepo;
    }

    @PostMapping("/register.do")
    public String register(String username, String password, HttpSession session) {
        // 1. 先检验用户名是否已存在
        UserDo userDo = userRepo.selectOneByUsername(username);
        if (userDo != null) {
            // 说明该用户名已存在
            return "redirect:./register.html";
        }
        // 2. 先对密码做好”加密“，保证数据库中保存的密码不是明文密码
        String salt = BCrypt.gensalt(); // 生成随机数据（盐值）
        password = BCrypt.hashpw(password, salt);
        // 3. 构造 userDo 对象
        UserDo newUserDo = new UserDo(username, password);
        userRepo.insert(newUserDo);
        UserSO userSO = new UserSO(newUserDo);
        session.setAttribute("currentUser", userSO);

        return "redirect:/studio/";
    }

    @PostMapping("/login.do")
    public String login(String username, String password, HttpServletRequest request) {

        // 1. 先根据用户名从表中查询出数据，用 UserDO 对象表示
        UserDo userDo = userRepo.selectOneByUsername(username);
        if (userDo == null) {
            // 说明用户输入的用户名就有问题
            return "redirect:./login.html";
        }
        // 2. 检查密码是否真正正确
        // plaintext : 明文密码 —— 用户刚才传入的密码
        // hashed : 经过 hash 后的密码 —— 从表中查出来的密码
        if (BCrypt.checkpw(password, userDo.password)) {
            // 返回 true，代表匹配，说明用户输入的密码没问题
            UserSO userSO = new UserSO(userDo);
            HttpSession session = request.getSession();
            session.setAttribute("currentUser", userSO);
            return "redirect:/studio/";
        } else {
            // 代表用户输入的密码肯定有问题
            return "redirect:./login.html";
        }
    }

    @GetMapping("/quit.do")
    public String quit(HttpServletRequest req) {
        HttpSession session = req.getSession(false);
        if (session != null) {
            session.removeAttribute("currentUser");
        }

        return "redirect:/studio/";
    }
}
